package com.itheima.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.itheima.tanhua.dubbo.mappers.FriendMapper;
import com.itheima.tanhua.dubbo.mappers.MovementLikeLogMapper;
import com.itheima.tanhua.dubbo.mappers.MovementMapper;
import com.itheima.tanhua.dubbo.mappers.MovementTimelineMapper;
import com.itheima.tanhua.model.domain.Friend;
import com.itheima.tanhua.model.domain.Movement;
import com.itheima.tanhua.model.domain.MovementLikeLog;
import com.itheima.tanhua.model.domain.MovementTimeline;
import com.itheima.tanhua.model.vo.MovementVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author itheima
 * @since 2022-03-06
 */
@Slf4j
@DubboService
public class MovementServiceImpl implements MovementService {

    @Autowired
    private MovementMapper movementMapper;

    @Autowired
    private MovementTimelineMapper movementTimelineMapper;

    @Autowired
    private FriendMapper friendMapper;

    @Autowired
    private MovementLikeLogMapper movementLikeLogMapper;

    @Override
    public Boolean sendMovement(Movement movement) {
        if (Objects.isNull(movement)) {
            log.warn("动态不能为空");
            return false;
        }

        // 步骤一：插入动态表
        int addResult = movementMapper.insertMovement(movement);
        if (addResult <= 0) {
            log.error("插入失败");
            return false;
        }

        // 步骤二：查询我的朋友列表
        List<Friend> friends = friendMapper.getFriendsByUserId(movement.getUserId().toString());
        if (CollUtil.isNotEmpty(friends)) {
            for (Friend friend : friends) {
                MovementTimeline timeline = new MovementTimeline();
                timeline.setMovementId(movement.getId());
                timeline.setFriendId(friend.getFriendId());
                timeline.setUserId(friend.getUserId());
                timeline.setCreated(new Date());
                timeline.setUpdated(new Date());
                movementTimelineMapper.insertMovementTimeline(timeline);
            }
        }

        return true;
    }

    @Override
    public List<MovementVo> getRecommendList(Integer page, Integer pageSize) {
        if (Objects.isNull(page)) {
            page = 1;
        }

        if (Objects.isNull(pageSize)) {
            pageSize = 10;
        }

        Integer skip = (page - 1) * pageSize;
        return movementMapper.getRecommendList(skip, pageSize);
    }

    @Override
    public Boolean addLikeLog(MovementLikeLog log) {
        return movementLikeLogMapper.insertLog(log) > 0;
    }
}
